﻿using TbShop.Business.Components;
using TbShop.Entity;
using TbShop.Web.Areas.Admin.Models;
using TbShop.Web.Helpers;
using TbShop.Web.Infrastructure;
using Newtonsoft.Json;
using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TbShop.Web.Areas.Admin.Controllers
{
    public class BannerController : BaseCacheManageController<Banner, BannerViewModel>
    {
        private ServiceComponents<Banner> bannerBC = new ServiceComponents<Banner>();

        public BannerController() : base("Banner", "Banner", "Banner") { }
        public override ActionResult Index()
        {
            ViewBag.Categories = GetAllBannerCategory();
            return base.Index();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public override ActionResult Edit(BannerViewModel model)
        {
            if (model.Id == 0)
            {
                if (Request.Files == null || Request.Files["image"] == null || Request.Files["image"].ContentLength == 0)
                {
                    SendMessage("主图不能为空", Constants.MessageType.Warning);
                    return RedirectToAction("Edit", new { id = (model == null ? 0 : model.Id) });
                }
            }
            if (Request.Files.Count > 0)
            {
                var file = this.Request.Files["image"];
                if (file != null && file.ContentLength > 0)
                    model.ImageUrl = ImageUrlHelper.SaveFileToUpload(file, StaticWords.UploadFolder.Banner);
            }
            var data = DataMapperHelper.Map<Banner>(model);
            data.FillEntity(User.Identity.Name);
            var saveResult = bannerBC.Save(data);
            if (saveResult != null)
            {
                OperationLogHelper.SaveOperationLog(AdminId, (model.Id > 0 ? "修改" : "添加"), "Banner", "", saveResult.Id.ToString());
                SendMessage("保存成功", Constants.MessageType.Success);
                return RedirectToAction("Index");
            }
            else
                SendMessage("保存失败", Constants.MessageType.Warning);
            return RedirectToAction("Edit", new { id = (saveResult == null ? 0 : saveResult.Id) });
        }

        /// <summary>
        /// 获取所有分类
        /// </summary>
        /// <returns></returns>
        public IEnumerable<SelectListItem> GetAllBannerCategory()
        {
            return CodeTableHelper.GetCodeTableDataByCategory(Constants.CodeCategories.BannerCategory).OrderBy(a => a.OrderNum).Select(a => new SelectListItem
            {
                Text = a.CodeDescription,
                Value = a.Code
            });
        }
    }
}